/** 
 * @Title: BBSSyn.java 
 * @Package com.zizo.autohome.word.syn.dao 
 * @Description: TODO
 * @author HeYan
 * @date 2016年9月13日 下午5:05:40 
 */
package com.zizo.autohome.word.syn.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import com.zizo.util.Analysis;
import com.zizo.util.ConnectionPool;

/**
 * @ClassName: BBSSyn
 * @Description: TODO 近义词替换
 * @author HeYan
 * @date 2016年9月13日 下午5:05:40
 * 
 */
public class NewsReplySynDao implements Runnable {
	private Connection conn;
	private String id;// tableName
	private Map<String, String> sys;

	/**
	 * @param conn
	 * @param id
	 * @param sys
	 */
	public NewsReplySynDao(Connection conn, String id, Map<String, String> sys) {
		super();
		this.conn = conn;
		this.id = id;
		this.sys = sys;
	}

	public void run() {
		getBBSData();
		System.out.println(id);
	}

	public final void getBBSData() {
		Statement st = null;
		ResultSet rs = null;
		String sql = "SELECT reply_id,reply_content FROM autohome_other." + id;
		try {
			st = conn.createStatement();
			rs = st.executeQuery(sql);
			while (rs.next()) {
				int bbs_id = rs.getInt("reply_id");
				String bbs_nr = rs.getString("reply_content");
				String nr = "";
				if (bbs_nr != null) {
					nr = Analysis.replaceSyn(bbs_nr, sys);
				}
				updateData(bbs_id, nr);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public final void updateData(int bbs_id, String nr) {
		PreparedStatement ps = null;
		String sql = "UPDATE autohome_other." + id + " SET reply_content=? WHERE reply_id=?";
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, nr);
			ps.setInt(2, bbs_id);
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @Title: getSyn
	 * @Description: 查找carvoice_autohome中topic_syn表中的数据对应，返回Map表，用于同义词的替换
	 * @return Map<String,String>
	 * @author HeYan
	 */
	public Map<String, String> getSyn() {
		Map<String, String> map = new HashMap<>();
		Statement st = null;
		ResultSet rs = null;
		String sql = "select syn_word,syn_syn from carvoice_autohome.topic_syn";
		try {
			st = conn.createStatement();
			rs = st.executeQuery(sql);
			while (rs.next()) {
				map.put(rs.getString("syn_word"), rs.getString("syn_syn"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * @param conn
	 */
	public NewsReplySynDao(Connection conn) {
		super();
		this.conn = conn;
	}

	public static void main(String[] args) {
		Connection conn = ConnectionPool.getConnection("autohome_syn", "localhost");
		NewsReplySynDao dao = new NewsReplySynDao(conn);
		Map<String, String> syn = dao.getSyn();
		NewsReplySynDao dao1 = new NewsReplySynDao(conn, "other_news_reply", syn);
		dao1.run();
	}
}
